package cz.proks.schoolpupilbook.gae.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;

import cz.proks.schoolpupilbook.gae.converter.Converter;
import cz.proks.schoolpupilbook.gae.converter.UserRelationConverter;
import cz.proks.schoolpupilbook.gae.dao.PersistenceManager.PersistenceExecutor;
import cz.proks.schoolpupilbook.gae.dbo.UserRelationDBO;
import cz.proks.schoolpupilbook.shared.domain.User;
import cz.proks.schoolpupilbook.shared.domain.UserRelation;

public class UserRelationDAO extends BaseDAO<UserRelationDBO, UserRelation> {

	@Override
	protected Class<UserRelationDBO> getDBOClass() {
		return UserRelationDBO.class;
	}
	
	@Override
	protected Converter<UserRelationDBO, UserRelation> getConverter() {
		return new UserRelationConverter();
	}
	
	@Override
	public void save(UserRelation domain) {
		if (!existsForRelation(domain.getParent(), domain.getStudent()));
			super.save(domain);
	}
	
	public boolean existsForRelation(final User parent, final User student) {
		if (parent == null || student == null)
			return false;
		
		return PersistenceManager.execute(new PersistenceExecutor<Boolean>() {						
			@Override
			public Boolean doExecute(EntityManager em) {				
				try {
					List<?> res = em.createQuery("SELECT FROM " + getDBOClass().getName() + " WHERE studentKey = :studentKey AND parentKey = :parentKey")
							 .setParameter("studentKey", student.getId())
							 .setParameter("parentKey", parent.getId())
							 .getResultList();
					
					return res != null && !res.isEmpty();
				} catch (NoResultException e) {
					return false;
				}				
			}
		}, false);
	}
}
